<?php
namespace Common\Action;
use Common\Action\FuncAction;
use Common\TagLib\yhxia_https;
/**
 * 前台控制器基类
 */
class TopAction extends FuncAction
{

protected function _initialize()
{
        if (false === ($setting = F('setting'))) {
            $setting = D('setting')->setting_cache();
        }	
C($setting);
$this->assign('async_sendmail', session('async_sendmail'));
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/history/disable_num_iids.php';
$dir=$basedir.'/data/Runtime/Data/history/pdddisable_num_iids.php';
$dir=$basedir.'/data/Runtime/Data/history/bindtime.php';
$ret=opcache_invalidate($dir,TRUE);
}
 $del_times = F('history/disable_num_iids');
 $NowTime=NOW_TIME;
 $bindtime = F('history/bindtime');
if(($NowTime - $bindtime)>900){
	$this->bindorder();
	 F('history/bindtime', $NowTime);
}

 if(($NowTime-$del_times)>2000){
 $where = 'coupon_end_time <'.$NowTime;
 M('items')->where($where)->delete();	
 F('history/disable_num_iids', $NowTime);
 }
    $del_pddtimes = F('history/pdddisable_num_iids');

    if(($NowTime-$del_pddtimes)>3600){
        $where = 'coupon_end_time <'.$NowTime;
        M('pdditems')->where($where)->delete();
        F('history/pdddisable_num_iids', $NowTime);
    }


$Now=NOW_TIME;
if(date('d',$Now)=='21'){
$iscreate=S('createfinance');
if(false === $iscreate){
$where=array(
		'add_time'=>date('Y-m-d',$Now),
		'type'=>1
);
$isset=M('finance')->where($where)->count();
if(!$isset){
$webmaster=M('user')->field('webmaster_rate,id,webmaster_pid,pdd_pid')->where('webmaster = 1')->select();
if($webmaster){
$BeginDate=date('Y-m-01', strtotime('-1 month'));	
$start=strtotime($BeginDate);
$end =date('Y-m-01', strtotime(date("Y-m-d")));
$end = strtotime($end);
$map['add_time'] = array(
            array(
                'egt',
                $start
            ),
            array(
                'elt',
                $end
            )
);
					
foreach($webmaster as $k=>$v){
$map['ad_id']=$v['webmaster_pid'];
$webmaster_rate=$v['webmaster_rate'];
$uid=$v['id'];
$fanxian=trim(C('yh_fanxian'));
$map['status']=3;
$map['nstatus']=0;
$cashback=0;	
$income =0;
$total_income=M('order')->where($map)->sum('income');
$income =round($total_income*($webmaster_rate/100),2);
$total_integral=M('order')->where($map)->sum('integral');
$cashback=round(($total_integral*($fanxian/100))*($webmaster_rate/100),2);
$payment=round($income-$cashback,2);
$data=array(
'add_time'=>date('Y-m-d',$Now),
'price'=>$income,
'mark'=>date('Y-m',$start),
'status'=>2,
'backcash'=>$cashback,
'income'=>$payment,
'uid'=>$uid,
'type'=>1
);
$result=M('finance')->add($data);
}

//duoduo start 
$dmap['order_settle_time'] = array(
            array(
                'egt',
                $start
            ),
            array(
                'elt',
                $end
            )
);

foreach($webmaster as $k=>$v){
$dmap['p_id']=$v['pdd_pid'];
$webmaster_rate=$v['webmaster_rate'];
$uid=$v['id'];
$map['order_status']='已结算';
$cashback=0;	
$income =0;
$total_income=M('pddorder')->where($dmap)->sum('promotion_amount');
$income =round($total_income*($webmaster_rate/100),2);
$payment=$income;
$data=array(
'add_time'=>date('Y-m-d',$Now),
'price'=>$income,
'mark'=>date('Y-m',$start),
'status'=>2,
'backcash'=>$cashback,
'income'=>$payment,
'uid'=>$uid,
'type'=>2
);
$result=M('finance')->add($data);
}


S('createfinance','ok',86400);
}	
		
			
						
}

}		
	
}
		
		
		
    }
    
   	protected function Fstatic($id){
		switch($id){
			case 2 :
			return '待付款';
			break;
			case 1 :
			return '已付款';
			break;
			default : 
			return '异常';
			break;
		}

	}
   
    
    public function _empty()
    {
        $this->_404();
    }
	
protected function check_verify($code, $id = ''){
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

Public  function verify(){
ob_end_clean();
$Verify =    new \Think\Verify();
$Verify->fontSize = 30;
$Verify->length   = 4;
$Verify->useCurve = false;
$Verify->useNoise = false;
$Verify->entry();
}


protected function bindorder(){
$where=array(
            'add_time'=>array('gt',strtotime("-10 day")),
            'nstatus' =>1,
            'uid'=>0
        );
$mod=M('order');	
$exist = $mod->field('id,income,oid')->where($where)->select();

$result = array();
foreach($exist as $val){
	$key=$val['oid'];
	if(!isset($result[$key])){
        $result[$key] = $val;
    }
        
}

if($exist){
$field='oid,fuid,guid,id';
$sql='';
$si=0;
foreach(array_values($result) as $s){
	
if($si==0){
$sql="(SELECT ".$field." from tqk_user where oid='". $s['oid'] ."' and status=1)";
}else{
$sql=$sql." union all (SELECT ".$field." from tqk_user where oid='". $s['oid'] ."' and status=1)";		
}
$si++;
}
$Model = M();
if($sql){
$list_child=$Model->cache(true, 5 * 60)->query($sql);

foreach($list_child as $m=>$h){
$listitem[$h['oid']]=$h;
}

foreach($exist as $k=>$v){
if($listitem[$v['oid']]['id']){
$data=array(
'uid'=>$listitem[$v['oid']]['id'],
'fuid'=>$listitem[$v['oid']]['fuid'],
'guid'=>$listitem[$v['oid']]['guid'],
);
$map=array(
'id'=>$v['id']
);
$mo=$mod->where($map)->save($data);

} 

}
 
}

}



}



protected function randStr($uid,$len = 6, $format = 'ALL')
{
    switch ($format) {
        case 'ALL':
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        break;
        case 'CHAR':
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        break;
        case 'HIGHER':
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        break;
        case 'LOWER':
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        break;
        case 'NUMBER':
        $chars = '0123456789';
        break;
        default:
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
        break;
    }
    mt_srand((double) microtime() * 1000000 * $uid);
    $password = "";
    while (strlen($password) < $len)
        $password .= substr($chars, (mt_rand() % strlen($chars)), 1);
    
    return $password;
}

 protected function _curl($url, $data = array(), $is_post = false, $cookie = null, $referer = null)
    {
        set_time_limit(30);
        $curl = curl_init();
        if($data && $is_post == false){
            $url .= '?' . http_build_query($data);
        }
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //
		curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //
		curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if($is_post){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        if($cookie){
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
       curl_setopt($curl, CURLOPT_REFERER, C('yh_site_url'));
       curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5' );  
        curl_setopt($curl, CURLOPT_TIMEOUT,30);
        $result = curl_exec($curl);
		//var_dump(curl_error($curl));
        curl_close($curl);
        if (empty($result)) {
            $result = false;
        }
        
        return $result;
    }



protected function create_token($key,$data=array()){
$ServerToken='';
foreach($data as $k=>$v){
	$ServerToken.=md5($v);
}
$ServerToken=md5($ServerToken .'_'.$key);
return $ServerToken;
}

/**
     * 图片上传处理
     * @param [String] $path [保存文件夹名称]
     * @param [String] $thumbWidth [缩略图宽度]
     * @param [String] $thumbHeight [缩略图高度]
     * @return [Array] [图片上传信息]
     */
        
protected function _upload($FILES,$path,$thumb=array()) {
        $obj = new \Think\Upload();// 实例化上传类
        $obj->maxSize = C('yh_attr_allow_size')*1024*1024 ;// 设置附件上传大小
        $obj->savePath =C('yh_attach_path').$path.'/'; // 设置附件上传目录
        $obj->exts = explode(',',C('yh_attr_allow_exts'));// 设置附件上传类型
        $obj->saveName = array('uniqid','');//文件名规则
        $obj->rootPath =ROOT_PATH.'/';
        $obj->replace = true;//存在同名文件覆盖
        $obj->autoSub = true;//使用子目录保存
        $obj->subName  = array('date','Ym');//子目录创建规则，
        $info = $obj->uploadOne($FILES);
        if(!$info) {
            return array('error' =>0, 'info'=> $obj->getError() );
        }else{
            if($thumb){  //生成缩略图
                $image = new \Think\Image();
                    $thumb_file =ROOT_PATH.'/'.$info['savepath'] . $info['savename'];
                    $save_path =ROOT_PATH.'/'.$info['savepath'] . 'thumb_' . $info['savename'];
				    $image->open( $thumb_file )->thumb( $thumb['width'], $thumb['height'],\Think\Image::IMAGE_THUMB_FILLED )->save( $save_path );
				    @unlink($thumb_file); //上传生成缩略图以后删除源文件
				    
				    return array(
                            'status' => 1,
                            'savepath' => $info['savepath'],
                            'savename' => $info['savename'],
                            'pic_path' => $info['savepath'] . $info['savename'],
                            'mini_pic' => '/'.$info['savepath'] . 'thumb_' .$info['savename']
                   );
            }else{
            	
             //   foreach($info as $file) {
                    return array(
                            'status' => 1,
                            'savepath' => $info['savepath'],
                            'savename' => $info['savename'],
                            'pic_path' => '/'.$info['savepath'].$info['savename']
                    );
               // }

            }
        }
    }
	
protected function getthemonth($date){
    $firstday = date('Y-m-01', $date);
    $lastday = date('Y-m-d', strtotime("$firstday +1 month"));
    return array(strtotime($firstday),strtotime($lastday));
}
	
    protected function _404($url = '')
    {
        if ($url) {
            redirect($url);
        } else {
            //send_http_status(404);
            $this->display('Index/404');
            exit;
        }
    }
    public function getItem($num_iid,$activityId){
 	$appkey = trim(C('yh_taobao_appkey'));
    	$appsecret = trim(C('yh_taobao_appsecret'));
    	if (! empty($appkey) && ! empty($appsecret) && !empty($num_iid)) {
    		vendor('taobao.taobao');
    		$c = new \TopClient();
    		$c->appkey = $appkey;
    		$c->secretKey = $appsecret;
    		$req = new \TbkItemInfoGetRequest();
    		$req->setFields("num_iid,user_type,title,seller_id,volume,nick,pict_url,reserve_price,zk_final_price,item_url");
    		$req->setPlatform("1");
    		$req->setNumIids($num_iid);
    		$resp = $c->execute($req);
    		$resparr = xmlToArray($resp);
    		$contents = $resparr['results']['n_tbk_item'];
		}

        if ($contents) {
			$info = array();
			$info['title'] = $contents['title'];
			$info['volume'] = $contents['volume'];
			$info['price'] = $contents['zk_final_price'];
			$info['pic_url'] = $contents['pict_url'];
			$info['pic_url'] = str_replace('_320x320.jpg', "", $info['pic_url']);
			$info['sellerId'] = $contents['seller_id'];
			$info['nick'] = $contents['nick'];
            if ($contents['user_type'] == "1") {
                $info['shop_type'] = "B";
            } else {
                $info['shop_type'] = "C";
            }
			$info['num_iid'] = $num_iid;
            $info['coupon_start_time'] = date('Y-m-d H:i', time());
            $info['coupon_end_time'] = date('Y-m-d H:i', time() + 86400 * 7);
			$descUrl = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $num_iid . '%22%7D';
            $yhxia_https = new yhxia_https();
            $yhxia_https->fetch($descUrl);
            $source = $yhxia_https->results;
            if (!$source) {
                $source = file_get_contents($descUrl);
            }
            $result_data = json_decode($source, true);
            $dinfo = array();
            $num = $result_data['data']['images'];
            for ($i = 0; $i < count($num); $i++) {
                $images = $i + 1;
                $desc[$images] = $num[$i];
                $desc[$images] = '<img class="lazy" src=' . $desc[$images] . '>';
            }
            $info['desc'] = $desc[1] . '' . $desc[2] . '' . $desc[3] . '' . $desc[4] . '' . $desc[5] . '' . $desc[6] . '' . $desc[7] . '' . $desc[8] . '' . $desc[9] . '' . $desc[10] . '' . $desc[11] . '' . $desc[12] . '' . $desc[13] . '' . $desc[14] . '' . $desc[15] . '' . $desc[16] . '' . $desc[17] . '' . $desc[18] . '' . $desc[19] . '' . $desc[20] . '' . $desc[21] . '' . $desc[22] . '' . $desc[23] . '' . $desc[24] . '' . $desc[25] . '' . $desc[26] . '' . $desc[27] . '' . $desc[28] . '' . $desc[29] . '' . $desc[30];
			
            return $info;
        } else {
            return false;
        }
    }
    public function http($url)
    {
        set_time_limit(0);
        $result = file_get_contents($url);
        if ($result === false) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($curl);
            curl_close($curl);
        }
        if (empty($result)) {
            $result = false;
        }
        return $result;
    }
    public function get_id($url)
    {
        $id = 0;
        $parse = parse_url($url);
        if (isset($parse['query'])) {
            parse_str($parse['query'], $params);
            if (isset($params['id'])) {
                $id = $params['id'];
            } elseif (isset($params['item_id'])) {
                $id = $params['item_id'];
            } elseif (isset($params['default_item_id'])) {
                $id = $params['default_item_id'];
            } elseif (isset($params['amp;id'])) {
                $id = $params['amp;id'];
            } elseif (isset($params['amp;item_id'])) {
                $id = $params['amp;item_id'];
            } elseif (isset($params['amp;default_item_id'])) {
                $id = $params['amp;default_item_id'];
            }
        }
        return $id;
    }
	
	
protected function getRobot(){
if(empty($_SERVER['HTTP_USER_AGENT']))
 {
  return false;
 }
 $searchEngineBot = array(
  'googlebot'=>'google',
  'mediapartners-google'=>'google',
  'baiduspider'=>'baidu',
  'msnbot'=>'msn',
  'dotbot'=>'dotbot',
  'youdaobot'=>'yodao',
  'yahoo! slurp'=>'yahoo',
  'yahoo! slurp china'=>'yahoo',
  'iaskspider'=>'iask',
  'sogou web spider'=>'sogou',
  'sogou push spider'=>'sogou',
  'sosospider'=>'soso',
  'bingbot'=>'bing',
  'yandexbot'=>'yan',
  'ahrefsbot'=>'ahrefs',
  '360Spider'=>'360',
  'sitemapx'=>'sitemapx',
  'spider'=>'other',
  'alibaba.security'=>'alibaba',
  'bot'=>'bot',
  'dotbot'=>'dotbot',
  'MJ12bot'=>'MJ12bot',
  'DeuSu'=>'DeuSu',
  'Swiftbot'=>'Swiftbot',
  'YandexBot'=>'YandexBot',
  'YisouSpider'=>'YisouSpider',
  'jikeSpider'=>'jikeSpider',
  'EasouSpider'=>'EasouSpider',
  'oBot'=>'oBot',
  'FlightDeckReports Bot'=>'FlightDeckReports',
  'crawler'=>'other',
 );
 $spider = strtolower($_SERVER['HTTP_USER_AGENT']);
 foreach ($searchEngineBot as $key => $value)
 { 
  if (strpos($spider, $key)!== false)
  {
   return $value;
  }
 }
 return false;
}
    
    /*
	 * 验证是否存在openid
	 */
	protected function verificat(){
		$openid = $_SESSION['user']['openid'];
		$json=array(                                 
			'status'=>'out',                             
			'msg'=>'登录超时'                                
		);  
	  	if(!$openid){
	  		exit(json_encode($json));
	  	}
	}  
     
}